package com.ls.fw.mvc.springmvc.support.aop;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.alibaba.fastjson.JSON;
import com.ls.fw.commons.log.exception.ExceptionsHelper;
import com.ls.fw.commons.log.support.LogAspect;
import com.ls.fw.commons.log.support.LogPara;
import com.ls.fw.mvc.springmvc.support.view.json.JsonView;


public class ControllerLogAspect extends LogAspect {
	
	@Override
	protected String handlArgs(ProceedingJoinPoint jp,Object[] args) {
		final Set<Object> set = new HashSet<Object>();
		final Set<Object> set1 = new HashSet<Object>();
		boolean flag = false;
		if(args!=null && args.length>=1){
			for (Object object : args) {
				if(object==null){
					continue;
				}
				if(object instanceof WebRequest){
					continue;
				}
				if(object instanceof ServletRequest){
					continue;
				}
				if(object instanceof ServletResponse){
					continue;
				}
				if(object instanceof BeanPropertyBindingResult){
					continue;
				}
				set1.add(object);
				LogPara logPara = object.getClass().getAnnotation(LogPara.class);
				if(logPara != null){
					set.add(object);
					flag = true;
				}
			}
		}
		if(!flag){
			try {
				return JSON.toJSONString(set1);
			} catch (Exception e) {
				this.logger.warn(ExceptionsHelper.getRootCause(e).getMessage(),e);
			}
		}
		try {
			return JSON.toJSONString(set);
		} catch (Exception e) {
			this.logger.warn(ExceptionsHelper.getRootCause(e).getMessage(),e);
		}
		return "";
	}

	@Override
	protected String handlResult(ProceedingJoinPoint jp,Object result,long startTime) {
		String returnInfo = "";
		boolean flag = false;
		if(result instanceof ModelAndView){
			ModelAndView modelAndView = (ModelAndView)result;
			View view = modelAndView.getView();
			if(view instanceof JsonView){
				JsonView dJsonView = (JsonView)view;
				try {
					returnInfo = JSON.toJSONString(dJsonView.filterModel(modelAndView.getModel()));
				} catch (Exception e) {
					this.logger.warn(ExceptionsHelper.getRootCause(e).getMessage(),e);
				} 
				flag = true;
			}
		}
		if(!flag){
			try {
				returnInfo = JSON.toJSONString(result);
			} catch (Exception e) {
				this.logger.warn(ExceptionsHelper.getRootCause(e).getMessage(),e);
			} 
		}
		return returnInfo;
	}
 
	 

}